﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Xml;
using AMS.Inventory.DataAccess;
using AMS.Inventory.Entities;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.Web.UI;

namespace AMSInventoryWeb.UserControls
{
    public partial class SelectAssetCtl : UserControl
    {
        private const string OBJ_ID = "Id";
        private const string PLAN_KEY_VALS = "PlanKeyVals";
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private PageBuilder m_PageBuilder;
        private  BaseDataManager m_Acc = new BaseDataManager();
        private UserDataSourceBuilder DataSourceBuilder
        {
            get { return (UserDataSourceBuilder) Session["DataSourceBuilder"]; }
            set { Session["DataSourceBuilder"] = value; }
        }

        public string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }

        public string ClassName
        {
            get { return hdnClassName.Value; }
            set { hdnClassName.Value = value; }
        }

        public string TypeName
        {
            get { return hdnTypeName.Value; }
            set { hdnTypeName.Value = value; }
        }

        public string PlanKeyVal
        {
            get { return hdnKeyVal.Value; }
            set
            {
                string val = value;
                if (val.Length == 0)
                    val = Guid.Empty.ToString();
                hdnKeyVal.Value = val;
            }
        }

        public string MenuId
        {
            get { return Request.QueryString["MenuId"]; }
        }

        public string PlanId
        {
            get { return Request.QueryString["Id"]; }
        }


        public StringCollection KeyVals
        {
            get { return ((StringCollection) Session[PLAN_KEY_VALS]); }
            set { Session[PLAN_KEY_VALS] = value; }
        }


        private string QueryCondition
        {
            get
            {
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }

        private string ReturnQueryStringValue(string keyString)
        {
            string strValue = Request.QueryString[keyString];
            if (strValue == null)
                strValue = "";
            return Convert.ToString(strValue);
        }


        protected override void OnInit(EventArgs e)
        {
            ClassName = ReturnQueryStringValue("ClassName");
            TypeName = ReturnQueryStringValue("TypeName");
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(Page, SettingXmlPath);

            XmlNode listSqlNode = m_PageBuilder.GetPgListSqlNode(ClassName, TypeName, PlanInfo.SELECT_ASSET_LIST_SQL);
            if (listSqlNode != null)
            {
                m_PageBuilder.SetPgListAttribute(pgList, listSqlNode, true, false, false);
            }

            base.OnInit(e);
        }

        public void SetCtlDisabled()
        {
            btnSelect.Enabled = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            if (!IsPostBack)
            {
                m_CreateCtlHlp.SetDdlCondition(pgList, ddlCondition);
                if (PlanId != null && PlanId.Length == 36)
                {
                    var objList = m_Acc.GetObjectList(new PlanInfo().GetType().Name, "Id", PlanId);
                    if (objList != null && objList.Count > 0)
                    {
                        var currentPlan = (PlanInfo)objList[0];
                        int iMaxAssetAmount = currentPlan.MaxAssetAmount;
                        txtMaxAssetAmount.Text = iMaxAssetAmount.ToString();
                    }
                }
            }
        }

  
        private PaginationGridDataSourceBuilder BindPgList()
        {
            string sql = m_PageBuilder.GetPgListSqlValue(ClassName, TypeName, PlanInfo.SELECT_ASSET_LIST_SQL);
            sql = sql.Replace("\r\n", " ").Replace("\t", " ");
            if (sql.IndexOf("{0}") > -1)
                sql = sql.Replace("{0}", PlanKeyVal);
            sql += " " + QueryCondition;
            DataSourceBuilder = new UserDataSourceBuilder(sql, pgList);
            return DataSourceBuilder;
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (ConditionSelector1.SelectedConditionString.Length > 0)
                QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            pgList.BindGrid();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            pgList.BindGrid();
        }


        protected void btnSelect_Click(object sender, EventArgs e)
        {

            var sbErrInfo = new StringBuilder();
            txtMaxAssetAmount.BackColor = Color.Transparent;
            if (txtMaxAssetAmount.Text.Length == 0)
            {
                sbErrInfo.Append("【单计划最大资产量】不能为空\r\n");
                txtMaxAssetAmount.BackColor = Color.Yellow;
            }
            else
            {
                Regex reg = new Regex("\\d+$");
                if (!reg.IsMatch(txtMaxAssetAmount.Text))
                {
                    sbErrInfo.Append("【单计划最大资产量】必需是大于0的整数\r\n");
                    txtMaxAssetAmount.BackColor = Color.Yellow;
                }
                else
                {
                    var iMaxCount = Convert.ToInt32(txtMaxAssetAmount.Text);
                    if (iMaxCount <= 0)
                    {
                        sbErrInfo.Append("【單計畫最大資產量】必需是大於0的整數\r\n");
                        txtMaxAssetAmount.BackColor = Color.Yellow;
                    }
                }
            }

           

            if (sbErrInfo.Length > 0)
            {
                Alert.MessageBox(sbErrInfo.ToString());
                return;
            }
            int maxAssetAmount = Convert.ToInt32(txtMaxAssetAmount.Text);
            var acc = new CoreDataAccess();
            acc.BeginTransaction();
            try
            {
                if (PlanId != null && PlanId.Length == 36)
                {
                    var objList = acc.GetObjectList(new PlanInfo().GetType().Name, "Id", PlanId);
                    if (objList != null && objList.Count > 0)
                    {
                        var currentPlan = (PlanInfo)objList[0];
                        currentPlan.MaxAssetAmount = int.Parse(txtMaxAssetAmount.Text);
                        acc.SaveOrUpdate(currentPlan);
                    }
                }
                var ndLedgerInfos = acc.GetObjectsByKeyValues(typeof(LedgerInfo).Name, OBJ_ID, DataSourceBuilder.PrimaryKeys);
                var alAssetInfos = new ArrayList();
                foreach (LedgerInfo obj in ndLedgerInfos.Values)
                {
                    var ivObj = new InventoryInfo();
                    ivObj.SetProByLedgerInfo(obj);
                    alAssetInfos.Add(ivObj);
                }
                var sbErrMsg = new StringBuilder();
                acc.SavePlan(new Guid(PlanKeyVal), alAssetInfos, maxAssetAmount, ref sbErrMsg);
                if (sbErrMsg.Length == 0)
                {
                    Alert.MessageBox("设置所带资产完成");
                    acc.Commit();
                }
                else
                {
                    Alert.MessageBox(sbErrMsg.ToString());
                    acc.RollBack();
                }
            }
            catch (Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }

            pgList.BindGrid();
        }

        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
            string strUrlVal = ("/BaseData/ObjEdit.aspx?IsNav=false&MenuId=" + MenuId + "&ClassName=" + typeof (LedgerInfo).Name +
                                "&Id=" + e.SelectedDataKeyValue);
            m_PageBuilder.ShowModalDialog(strUrlVal, Page, typeof (LedgerInfo).Name, "");
        }
    }
}